from math import sqrt, ceil
import sys

class StatTracker:
    def __init__ (self):
        self.min = sys.maxint
        self.max = 0
        self.lastTime = 0
        self.elapsedTime = 0
        self.sum = 0.0
        self.sumOfSquares = 0.0
        self.last = None
        
    def loadStat(self, mean, max, min, stdDev, last, utcTime, elapsedTime):
        self.min = min
        self.max = max
        self.last = last
        self.sum = mean * elapsedTime
        self.sumOfSquares = stdDev * stdDev * (elapsedTime - 1) + self.sum*self.sum/elapsedTime    
        self.elapsedTime = elapsedTime
        self.lastTime = utcTime

    def updateStat(self, value, time):
        if (self.last != None):
            elTime = time - self.lastTime
            self.sum += self.last*elTime
            self.sumOfSquares += self.last*self.last*elTime
            self.elapsedTime += elTime
        self.min = min(self.min, value)
        self.max = max(self.max, value)
        self.lastTime = time
        self.last = value

    def mean(self):
        if self.elapsedTime > 0:
            return self.sum/self.elapsedTime
        else:
            return 0

    def stdDev(self):
        if self.elapsedTime > 1:
            x = (1.0 / (self.elapsedTime - 1) * (self.sumOfSquares - self.sum*self.sum/self.elapsedTime))
            if x > 0: #it shouldn't be possible for x to be < 0, but if x is close to 0, float rounding errors may make it < 0
                return sqrt(x)
        return 0